package com.darren.euc.interceptor;

import com.darren.euc.entity.Member;
import com.darren.euc.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 全局拦截器，拦截处理登录状态等
 * Created by JUECHENG at 2018/3/12 13:15.
 */
public class GlobInterceptor implements HandlerInterceptor {

    private List<String> exceptUrls;

    public List<String> getExceptUrls() {
        return exceptUrls;
    }

    public void setExceptUrls(List<String> exceptUrls) {
        this.exceptUrls = exceptUrls;
    }

    @Autowired
    private MemberService memberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String requestUri = request.getRequestURI();
        //放行exceptUrls中配置的url
        for (String url : exceptUrls) {
            if(url.endsWith("/**")){
                if (requestUri.startsWith(url.substring(0, url.length() - 3))) {
                    return true;
                }
            } else if (requestUri.startsWith(url)) {
                return true;
            }
        }

        //登录状态拦截 处理
        String token = request.getHeader("token");
        if (token == null || token.isEmpty())
            token = request.getParameter("token");
        Member member = memberService.findByToken(token);
        //将app登录用户信息设置到member
        request.setAttribute("member", member);
        request.setAttribute("token", token);

        //其他拦截。。。

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
